package com.dctp.ems.controller;

import com.alibaba.fastjson.JSONObject;
import com.dctp.common.controller.BaseController;
import com.dctp.common.utils.DateUtil;
import com.dctp.common.utils.StringUtil;
import com.dctp.common.cache.UserCache;
import com.dctp.common.vo.JsonResult;
import com.dctp.common.vo.PageResult;
import com.dctp.common.vo.QueryResult;
import com.jfinal.aop.Before;
import com.jfinal.core.Path;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import java.util.ArrayList;
import java.util.List;
import java.time.LocalDateTime;

import com.jfinal.plugin.activerecord.tx.Tx;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.servlet.http.HttpServletResponse;

@Path("/commission")
public class CommissionController extends BaseController {

    /**
     * GET /commission/list
     * 分页查询分佣记录，支持user_id、order_id、role_id、create_time范围
     */
    public void list() {
        int page = getInt("currentPage", 1);
        int pageSize = getInt("pageSize", 10);
        QueryResult qr = buildCommissionQuery();
        String select = "SELECT * ";
        String from = "FROM dctp_commission_record" + qr.where + " ORDER BY id DESC";
        var p = Db.paginate(page, pageSize, select, from, qr.params.toArray());
        List<Record> list = p.getList();
        for (Record r : list) {
            r.set("user", UserCache.getBasic(r.getLong("user_id")));
            r.set("src_user", UserCache.getBasic(r.getLong("order_user_id")));
        }
        renderJson(JsonResult.successWithData(
            new PageResult<>(list, p.getTotalRow(), pageSize, page)
        ));
    }

    /**
     * GET /commission/export
     * 导出分佣记录Excel，支持user_id、order_id、role_id、create_time范围
     */
    public void export() {
        int pageSize = 10000; // 导出最大行数
        QueryResult qr = buildCommissionQuery();
        String sql = "SELECT * FROM dctp_commission_record" + qr.where + " ORDER BY id DESC LIMIT ?";
        qr.params.add(pageSize);
        List<Record> list = Db.find(sql, qr.params.toArray());
        for (Record r : list) {
            Long uid = r.getLong("user_id");
            if (uid != null) {
                Record user = UserCache.getBasic(uid);
                r.set("user", user != null ? user.getColumns() : null);
            }
            Long orderUid = r.getLong("order_user_id");
            if (orderUid != null) {
                Record orderUser = UserCache.getBasic(orderUid);
                r.set("order_user", orderUser != null ? orderUser.getColumns() : null);
            }
            LocalDateTime createTime = r.getLocalDateTime("create_time");
            if (createTime != null) {
                r.set("create_time", DateUtil.format(createTime));
            }
        }
        try (Workbook wb = new XSSFWorkbook()) {
            Sheet sheet = wb.createSheet("分佣记录");
            // 表头
            String[] fields = {"id", "user_id", "order_id", "order_user_id", "service_fee", "fr_amount", "ratio", "role_id", "create_time", "remark"};
            String[] titles = {"ID", "用户ID", "订单ID", "订单用户ID", "服务费", "分佣金额", "分佣比例", "角色", "分佣时间", "备注"};
            Row head = sheet.createRow(0);
            for (int i = 0; i < titles.length; i++) {
                head.createCell(i).setCellValue(titles[i]);
            }
            // 数据
            int rowIdx = 1;
            for (Record r : list) {
                Row row = sheet.createRow(rowIdx++);
                for (int i = 0; i < fields.length; i++) {
                    Object val = r.get(fields[i]);
                    if (val == null) {
                        row.createCell(i).setCellValue("");
                    } else if (val instanceof Number) {
                        row.createCell(i).setCellValue(((Number) val).toString());
                    } else {
                        row.createCell(i).setCellValue(val.toString());
                    }
                }
            }
            // 响应下载
            HttpServletResponse resp = getResponse();
            String fileName = "commission_record_" + DateUtil.format(DateUtil.now(), "yyyyMMddHHmmss") + ".xlsx";
            resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            resp.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            wb.write(resp.getOutputStream());
            renderNull();
        } catch (Exception e) {
            renderJson(JsonResult.failWithMessage("导出失败: " + e.getMessage()));
        }
    }

    private QueryResult buildCommissionQuery() {
        Long userId = getParaToLong("user_id");
        Long orderId = getParaToLong("order_id");
        Long orderUserId = getParaToLong("order_user_id");
        Long roleId = getParaToLong("role_id");
        String startTime = getPara("start_time");
        String endTime = getPara("end_time");
        StringBuilder where = new StringBuilder(" WHERE 1=1 ");
        List<Object> params = new ArrayList<>();
        if (userId != null) {
            where.append(" AND user_id = ?");
            params.add(userId);
        }
        if (orderId != null) {
            where.append(" AND order_id = ?");
            params.add(orderId);
        }
        if (orderUserId != null) {
            where.append(" AND order_user_id = ?");
            params.add(orderUserId);
        }
        if (roleId != null) {
            where.append(" AND role_id = ?");
            params.add(roleId);
        }
        if (startTime != null && !startTime.isEmpty()) {
            where.append(" AND create_time >= ?");
            params.add(startTime);
        }
        if (endTime != null && !endTime.isEmpty()) {
            where.append(" AND create_time <= ?");
            params.add(endTime);
        }

        Integer frType = getParaToInt("fr_type");
        if( null != frType ){
            where.append(" AND fr_type = ?");
            params.add(frType);
        }

        String statDay = getPara("stat_day");
        if (StringUtil.isNotEmpty(statDay)) {
            where.append(" AND stat_day = ?");
            params.add(statDay);
        }

        String filterField = getFilterField();
        if (filterField != null) {
            where.append(" AND ").append(filterField).append(" = ?");
            params.add(getRequestUser().getLong("user_id"));
        }

        String roleKey = getPara("roleKey");
        Long roleUserId = getParaToLong("roleUserId");
        if (StringUtil.isNotEmpty(roleKey) && null != roleUserId) {
            where.append(" AND ").append(roleKey).append(" = ?");
            params.add(roleUserId);
        }

        return new QueryResult(where, params);
    }


    /**
     * GET /activity/getTrainConfig
     * 获取活动手数配置列表
     * 参数：activity 活动ID
     */
    public void getRatio() {
        Long roleId = getParaToLong("role_id");
        if (null == roleId) {
            renderJson(JsonResult.failWithMessage("参数缺失"));
            return;
        }
        List<Record> list = Db.find("SELECT * FROM dctp_commission_config WHERE role_id = ? ORDER BY down_limit ASC", roleId);
        renderJson(JsonResult.successWithData(list));
    }

    /**
     * POST /activity/setTrainConfig
     * 批量新增或更新活动手数配置
     * 请求体：{ activity: 活动ID, configs: [{down_limit, up_limit, quantity, id?}] }
     */
    @Before(Tx.class)
    public void setRatio() {
        Record body = jsonBody();
        Long roleId = body.getLong("role_id");
        List<JSONObject> configs = body.get("configs");
        if (null == roleId) {
            renderJson(JsonResult.failWithMessage("参数缺失"));
            return;
        }
        // 先删除该活动下所有配置
        Db.update("DELETE FROM dctp_commission_config WHERE role_id = ?", roleId);
        // 批量插入
        for (JSONObject config : configs) {
            config.put("role_id", roleId);
            config.remove("id"); // 保证自增
            config.put("create_time", DateUtil.now());
            Db.save("dctp_commission_config", new Record().put(config.getInnerMap()));
        }
        renderJson(JsonResult.success());
    }

}
